/**
 * 存储localstorage时候最好是封装一个自己的键值，
 * 在这个值里存储自己的内容对象，封装一个方法针对自己对象进行操作。
 * 避免冲突也会在开发中更方便。
 * @type {{set, get, remove, init, clear}}
 */
import config from '../../build/config';

let storageUtil = {
    namespace: config.appName,
};

storageUtil.getStorage = function () {
    if (!window.localStorage) {
        alert("浏览器支持localstorage");
        return {};
    }
    return window.localStorage;
};

storageUtil.set = function(key, value){
    const storage = storageUtil.getStorage();

    //存储
    let mydata = storage.getItem(storageUtil.namespace);

    if(!mydata){
        storageUtil.init();
        mydata = storage.getItem(storageUtil.namespace);
    }
    mydata = JSON.parse(mydata);

    mydata.data[key] = value;
    storage.setItem(storageUtil.namespace, JSON.stringify(mydata));

    return mydata.data;

};

storageUtil.get = function(key) {
    const storage = storageUtil.getStorage();
    //读取
    let mydata = storage.getItem(storageUtil.namespace);

    if(!mydata){
        return false;
    }
    mydata = JSON.parse(mydata);

    return mydata.data[key];
};

storageUtil.remove = function(key) {
    const storage = storageUtil.getStorage();

    //读取
    let mydata = storage.getItem(storageUtil.namespace);

    if(!mydata){
        return false;
    }

    mydata = JSON.parse(mydata);
    delete mydata.data[key];

    storage.setItem(storageUtil.namespace, JSON.stringify(mydata));

    return mydata.data;
};

storageUtil.clear = function(){
    const storage = storageUtil.getStorage();

    //清除对象
    storage.removeItem(storageUtil.namespace);
};

storageUtil.init = function(){
    const storage = storageUtil.getStorage();

    storage.setItem(storageUtil.namespace, '{"data":{}}');
};

export default storageUtil;